"use strict"
const mvc = require("cosjs.mvc");
const handle = mvc.library("handle","渠道接入","branch/opensdk")


exports.index = function(){
    let data= {"opensdk":this.library("opensdk/list") }
    return  handle.index.call(this,data);
}

exports.page = handle.page;

exports.save = handle.save;

exports.configure = function () {
    this.view = 'setting/opensdk'
    let id = this.get('id');
    if(!id){
        return this.error('args[id] empty');
    }
    let branch = this.branch;
    let opensdk = this.model("branch/opensdk/",branch);
    return opensdk.get(id).then(ret=>{
        if(!ret){
            return this.error('opensdk empty');
        }
        let key = ret['key'];
        let setting = ret['setting']||{};
        ret['fields'] = [];
        let fields = this.library("opensdk/fields",key);
        for(let k in fields){
            let v;
            if(k in setting){
                v = setting[k];
            }
            else{
                v = fields[k]['val'];
            }
            let d = {key:k,val:v,name:fields[k]['name']||k,option:fields[k]['option']||null };
            ret['fields'].push(d);
        }
        return ret;
    });
}

exports.configureSave = function(){
    this.output = "json";
    let id = this.get('id');
    if(!id){
        return this.error('ID不能为空');
    }
    let branch = this.branch;
    let opensdk = this.model("branch/opensdk/",branch);
    return opensdk.get(id).then(ret=>{
        if(!ret){
            return this.error('opensdk empty');
        }
        let key = ret['key'],info={};
        let fields = this.library("/opensdk/fields",key);
        if(!fields){
            return this.error('opensdk fields empty');
        }
        for (let k in fields) {
            info[k] = this.get(k, fields[k]['type']) ;
        }
        return opensdk.set(id,'setting',info,this.callback);
        
    })
}